﻿/**********************************************************************/
/*                                                                    */
/*                   embDocumentInhalator                             */
/*             http://embdocumentinhalator.codeplex.com/              */
/*                                                                    */
/*               (c) Copyright 2010 Ilija Injac         .             */
/*                                                                    */
/*  This source is subject to the CDDL License                        */
/*  http://embdocumentinhalator.codeplex.com/license                  */
/*                                                                    */
/*                                                                    */
/**********************************************************************/
using System;
using System.ComponentModel;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.UserCode;
using Microsoft.SharePoint.Utilities;
using System.Collections;
using System.Web;
using System.Text;
using embImage2Pdf;


namespace embDocumentInhalator.embDocInhalatorWebPartSandboxed
{
    /// <summary>
    /// The documentInhalator Webpart.
    /// </summary>
    /// This element was inserted by injac on machine PLATINCHECKER.
    /// 24.01.2011,18:14
    [ToolboxItem(false)]
    public partial class embDocInhalatorWebPartSandboxed : System.Web.UI.WebControls.WebParts.WebPart
    {

        FileSystemHelpers _FileSystemFuncitons = new FileSystemHelpers();
        /// <summary>
        /// Holds the URL for the javascript stuff.
        /// </summary>
        const string jsScriptURL = "/_catalogs/masterpage/jsFunctions.js";


        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,18:14
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            EnsureScriptManager();
            InitializeControl();
            this.ScanButton.Text = "Select Scanner";
            
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            //include the java script stuff
            HtmlGenericControl scriptInclude = new HtmlGenericControl("script");
            scriptInclude.Attributes.Add("src",
                                   SPContext.Current.Site.RootWeb.Url + jsScriptURL);
            Controls.Add(scriptInclude);

 
        }
        /// <summary>
        /// Ensures the script manager.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,18:15
        /// Taken from the web. From Bastians Blog.
        private void EnsureScriptManager() { 
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page); 
            if (scriptManager == null) { scriptManager = new ScriptManager();
                scriptManager.EnablePartialRendering = true;
                scriptManager.AsyncPostBackTimeout = 1500;
                if (Page.Form != null) { Page.Form.Controls.AddAt(0, scriptManager); } } }



        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,18:17
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }



        /// <summary>
        /// Handles the Click event of the ScanButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,18:15
        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            #region comments
            /*SPUserCodeService service = SPUserCodeService.Local;
            if (service != null)
            {
                int count = service.ProxyOperationTypes.Count;
                this._ShowStatus.Text += "Proxy count: " + count.ToString() + Environment.NewLine;
                foreach (SPProxyOperationType item in service.ProxyOperationTypes)
                {
                    this._ShowStatus.Text += "AssemblyName: " + item.AssemblyName +
                        Environment.NewLine + "TypeName: " + item.TypeName +
                        Environment.NewLine;
                }
            }*/
            #endregion

            if (ScanButton.Text == "Select Scanner")
            {
                EnlistScanners();
            }
            else if (ScanButton.Text == "Scan Image")
            {

                ScannerSettings scanSettings =
                    new ScannerSettings();

                scanSettings.ColorMode = DropDownColorMode.SelectedValue;
                if (txtDPI.Text == string.Empty)
                {
                    scanSettings.ResParamX = 75;
                    scanSettings.ResParamY = 75;
                }
                else
                {
                    if(txtDPI.Text.IsNumeric())
                    {
                        scanSettings.ResParamX = System.Convert.ToInt32(txtDPI.Text);
                        scanSettings.ResParamY = System.Convert.ToInt32(txtDPI.Text);
                    }
                    else
                    {
                        scanSettings.ResParamX = 75;
                        scanSettings.ResParamY = 75;
                    }
                }
                
                scanSettings.ImageFormat = GetWIAFileFormat(DropDownImageType.SelectedValue);
                //scanSettings.BitsPerPixel = System.Convert.ToInt32(DropDownColorMode.SelectedValue.Substring(
                //    0,2));

                scanSettings.PreferedColorMode = embWIAScan.embWIAFlatbedScan.GetColorMode(DropDownColorMode.SelectedValue);

                ScanImage(txtFileName.Text,scanSettings);
                
                
            }

           
        }

       

        /// <summary>
        /// Gets the WIA file format. This is the IMAGE format to be scanned.
        /// </summary>
        /// <param name="extensionShortcut">The extension shortcut.</param>
        /// <returns></returns>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 28.01.2011,22:55
        private string GetWIAFileFormat(string extensionShortcut)
        {
            string format = string.Empty;

            switch (extensionShortcut.ToUpper())
            {
                case ".BMP":
                    format = embWIAScan.WIAConstants.wiaFormatBMP;
                    break;
                case ".PNG":
                    format = embWIAScan.WIAConstants.wiaFormatPNG;
                    break;
                case ".GIF":
                    format = embWIAScan.WIAConstants.wiaFormatGIF;
                    break;
                case ".JPEG":
                    format = embWIAScan.WIAConstants.wiaFormatJPEG;
                    break;
                case ".TIFF":
                    format = embWIAScan.WIAConstants.wiaFormatTIFF;
                    break;
                case ".PDF":
                    format = embWIAScan.WIAConstants.wiaFormatTIFF;
                    break;

            }

            return format;
        }

        /// <summary>
        /// Enumerates the lists in site.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,18:16
        public void EnumerateListsInSite()
        {
            string[] systemLists = new string[] {
                                                    "fpdatasources",
                                                    "List Template Gallery",
                                                    "Master Page Gallery",
                                                   // "Site Assets",
                                                    "Site Pages",
                                                    "Solution Gallery",
                                                    "Style Library",
                                                    "Theme Gallery",
                                                    "Web Part Gallery",
                                                    "Converted Forms",
                                                    "Customized Reports",
                                                    "Form Templates",
                                                    "Reporting Templates",
                                                    "wfpub"
            };
            using (SPWeb oWebsite = SPContext.Current.Web)
            {

                foreach (SPList list in oWebsite.Lists)
                {
                    if (list is SPDocumentLibrary || list.BaseTemplate == SPListTemplateType.PictureLibrary)
                    {
                        if (!Array.Exists<string>(systemLists, e => e.Equals(list.Title)))
                        {
                            ListItem item = new ListItem();
                            item.Text = list.Title;
                            item.Value = oWebsite.GetFolder(list.Title).Url;
                            ListDropdown.Items.Add(list.Title);
                        }
                    }
                }
            }

        }

        /// <summary>
        /// Enlists the scanners.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,17:01
        public void EnlistScanners()
        {
            //Here is the click implementation
            try
            {
                StatusLabel.Text = "Searching for scanners...";

                ArrayList scanners = new ArrayList();

                //Test = SPUtility.ExecuteRegisteredProxyOperation(
                //            "embScannerProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0444acbbd0e19b4f",
                //            "embSPScanExpert.Proxy.ScanOperation",
                //            new embSPScanExpert.Proxy.ScannerArgs("Test")).ToString();

                scanners = (ArrayList)SPUtility.ExecuteRegisteredProxyOperation(
                             "embScannerProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0444acbbd0e19b4f",
                             "embSPScanExpert.Proxy.EnumerateScanners",
                             new embSPScanExpert.Proxy.ScannerEnumArgs());

                FillScannersDropDown(DropDownList1,ListDropdown,scanners,StatusLabel,ScanButton);

            }
            catch (Exception ex)
            {
                //_ShowStatus.Text = ex.StackTrace + ex.Message + ex.Source;
                StatusLabel.Text = ex.Message;
            }
        }



        /// <summary>
        /// Fills the scanners drop down.
        /// </summary>
        /// <param name="dropDown">The drop down.</param>
        /// <param name="libraryDropDown">The library drop down.</param>
        /// <param name="scanners">The scanners.</param>
        /// <param name="statusLabel">The status label.</param>
        /// <param name="scanButton">The scan button.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,17:26
        private void FillScannersDropDown(DropDownList dropDown,DropDownList libraryDropDown, 
            ArrayList scanners,Label statusLabel,Button scanButton)
        {
            if (scanners.Count > 0)
               {

                   dropDown.Visible = true;
                   //string test = string.Empty;
                   dropDown.Items.Clear();

                   foreach (string scanner in scanners)
                   {
                       //test += "" + scanner;
                       dropDown.Items.Add(scanner);
                   }
                   
                   statusLabel.Text = String.Format("Found {0} Scanners.", scanners.Count);
                   scanButton.Text = "Scan Image";

                   //Enlist lists
                   libraryDropDown.Visible = true;
                   EnumerateListsInSite();
               }
               else
               {
                   dropDown.Visible = false;
                   libraryDropDown.Visible = false;
                   statusLabel.Text = "No Scanners could be found. Please check your configurations";
               }
            
        }


        /// <summary>
        /// Scans the image.
        /// </summary>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,17:00
        public void ScanImage(string fileName,ScannerSettings scanSettings)
        {
            bool isPdf = false;

            if (this.DropDownImageType.SelectedValue.ToUpper() == ".PDF")
            {
                scanSettings.ImageFormat = embWIAScan.WIAConstants.wiaFormatTIFF;
                isPdf = true;
            }

            byte[] ImageData = (byte[])SPUtility.ExecuteRegisteredProxyOperation(
                       "embScannerProxy, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0444acbbd0e19b4f",
                       "embSPScanExpert.Proxy.ScanOperation",
                       new embSPScanExpert.Proxy.ScannerArgs(scanSettings.ImageFormat,
                           DropDownList1.SelectedValue, scanSettings.ResParamX,this.DropDownColorMode.SelectedValue));
            if (!isPdf)
            {
                SaveImageToLibrary(ImageData, ListDropdown, fileName, DropDownImageType.SelectedValue);
            }
            else
            {
                SavePdfToLibrary(ImageData,ListDropdown, fileName, ".pdf");
            }
            
        }



        /// <summary>
        /// Saves the image to library.
        /// </summary>
        /// <param name="ImageData">The image data.</param>
        /// <param name="libraryDropDown">The library drop down.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileExtension">The file extension.</param>
        /// This element was inserted by injac on machine PLATINCHECKER.
        /// 24.01.2011,17:15
        private void SaveImageToLibrary(byte[] ImageData, DropDownList libraryDropDown, string fileName,string fileExtension)
        {
           
            using (SPWeb oWebsite = SPContext.Current.Web)
            {
                string folder = string.Empty;
                System.Drawing.Image bw;

                BitmapConversions bcons = new BitmapConversions();

                if (oWebsite.Lists[libraryDropDown.SelectedItem.Text] is SPDocumentLibrary)
                {
                    folder = oWebsite.Lists[libraryDropDown.SelectedItem.Text].RootFolder.Url;
                }
                else
                {
                    folder = libraryDropDown.SelectedValue;
                }
                fileName = _FileSystemFuncitons.ConvertToValidSharePointFileName(fileName);
                SPFileCollection oFiles = oWebsite.GetFolder(folder).Files;
                string destUrl = SPEncode.UrlEncodeAsUrl(oFiles.Folder.ServerRelativeUrl) + "/" + 
                    fileName + fileExtension;

                if (DropDownColorMode.SelectedValue.Contains("gs"))
                {
                    bw = bcons.ByteArrayToImage(ImageData);
                    System.Drawing.Bitmap bwmap = bcons.ConvertToGrayscale((System.Drawing.Bitmap)bw);
                    ImageData = bcons.ImageToByteArray(((System.Drawing.Image)bwmap),bw.RawFormat);
                }

                SPFile oFileNew = oFiles.Add(destUrl, ImageData, true);
                SPListItem oListItem = oFileNew.Item;
                oListItem.Update();
                //Add link to edit the metadata of the currently scanned document
                editdocumentlink.NavigateUrl = string.Concat("javascript: ShowDialog('",
                                  SPContext.Current.Site.RootWeb.Url,
                                  "/",
                                  SPEncode.UrlEncodeAsUrl(
                                  oWebsite.Lists[libraryDropDown.SelectedItem.Text].RootFolder.Url),
                                  "/Forms/EditForm.aspx?ID=",
                                  oFileNew.Item.ID.ToString(),
                                 "')");
                
                //Shared%20Documents/Forms/EditForm.aspx?ID=1
                //&IsDlg=1

                //SPUtility.
                //SPUtility.Redirect(this.GetEditFormUrl(spfile), SPRedirectFlags.Default, this.Context);
                this.StatusLabel.Text = string.Format("Image saved to {0} list with filename {1}", libraryDropDown.SelectedItem.Text, fileName);
                           
                

            }
        }

        /// <summary>
        /// Saves the PDF to library.
        /// </summary>
        /// <param name="ImageData">The image data.</param>
        /// <param name="libraryDropDown">The library drop down.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileExtension">The file extension.</param>
        private void SavePdfToLibrary(byte[] ImageData, DropDownList libraryDropDown, string fileName, string fileExtension)
        {

            using (SPWeb oWebsite = SPContext.Current.Web)
            {
                string folder = string.Empty;
                System.Drawing.Image bw;
                Image2Pdf pdfConverter = new Image2Pdf();

                BitmapConversions bcons = new BitmapConversions();

                if (oWebsite.Lists[libraryDropDown.SelectedItem.Text] is SPDocumentLibrary)
                {
                    folder = oWebsite.Lists[libraryDropDown.SelectedItem.Text].RootFolder.Url;
                }
                else
                {
                    folder = libraryDropDown.SelectedValue;
                }
                fileName = _FileSystemFuncitons.ConvertToValidSharePointFileName(fileName);
                SPFileCollection oFiles = oWebsite.GetFolder(folder).Files;
                string destUrl = SPEncode.UrlEncodeAsUrl(oFiles.Folder.ServerRelativeUrl) + "/" +
                    fileName + fileExtension;

                if (DropDownColorMode.SelectedValue.Contains("gs"))
                {
                    bw = bcons.ByteArrayToImage(ImageData);
                    System.Drawing.Bitmap bwmap = bcons.ConvertToGrayscale((System.Drawing.Bitmap)bw);
                    ImageData = bcons.ImageToByteArray(((System.Drawing.Image)bwmap), bw.RawFormat);
                }

                SPFile oFileNew = oFiles.Add(destUrl, pdfConverter.CreatePdf(ImageData), true);
                SPListItem oListItem = oFileNew.Item;
                oListItem.Update();
                //Add link to edit the metadata of the currently scanned document
                editdocumentlink.NavigateUrl = string.Concat("javascript: ShowDialog('",
                                  SPContext.Current.Site.RootWeb.Url,
                                  "/",
                                  SPEncode.UrlEncodeAsUrl(
                                  oWebsite.Lists[libraryDropDown.SelectedItem.Text].RootFolder.Url),
                                  "/Forms/EditForm.aspx?ID=",
                                  oFileNew.Item.ID.ToString(),
                                 "')");

                //Shared%20Documents/Forms/EditForm.aspx?ID=1
                //&IsDlg=1

                //SPUtility.
                //SPUtility.Redirect(this.GetEditFormUrl(spfile), SPRedirectFlags.Default, this.Context);
                this.StatusLabel.Text = string.Format("Image saved to {0} list with filename {1}", libraryDropDown.SelectedItem.Text, fileName);



            }
        }

    }




    //public class ProgressTemplate : ITemplate
    //{
    //    private string template;

    //    public ProgressTemplate(string temp)
    //    {
    //        template = temp;
    //    }

    //    public void InstantiateIn(Control container)
    //    {
    //        LiteralControl ltr = new LiteralControl(this.template);
    //        container.Controls.Add(ltr);
    //    }
    //}

    
}
